<template>
  <div>
    <div class="box">
      <!-- 搜索 -->
      <div class="serch">
        <div class="header">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <div class="tb_box">
                <span class="tb_text">阵地名称</span>
                <input
                  class="tb_input"
                  type="text"
                  v-model="serch_position_name"
                  placeholder="请输入"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <div class="tb_box">
                <span class="tb_text">&nbsp;</span>
                <el-button type="primary" class="table_btn" @click="search">
                  <el-icon> <Search /> </el-icon>
                  搜索
                </el-button>
                <el-button class="table_btn" @click="reset">
                  <el-icon> <Refresh /> </el-icon>
                  重置
                </el-button>
                <el-button
                  type="success"
                  class="table_btn"
                  @click="openAddTerritory(0)"
                >
                  <el-icon><Plus /></el-icon>
                  添加
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 表格 -->
      <div class="table">
        <el-table
          type="index"
          :data="tableData"
          :key="index"
          max-height="100%"
          style="width: 100% !important; overflow: hidden"
          stripe
          v-loading="Loading"
        >
          <el-table-column type="index" label="序号" width="60px" />
          <el-table-column prop="position_name" label="阵地名" />
          <el-table-column prop="province" label="省份" />
          <el-table-column prop="district" label="区" />
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag type="primary" v-if="row.status == 0">开放</el-tag>
              <el-tag type="danger" v-else>未开放</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="position_intro" label="阵地简介" />
          <el-table-column prop="reservation_method" label="预约方式" />
          <el-table-column prop="visit_duration" label="游览时长（小时）" />
          <el-table-column prop="position_address" label="阵地地址" />
          <el-table-column prop="image_path" label="阵地图片">
            <template #default="{ row }">
              <img
                :src="`http://127.0.0.1:8000${row.image_path}`"
                alt=""
                style="width: 95%"
              />
            </template>
          </el-table-column>

          <el-table-column label="操作" class="Operation" width="200px">
            <template #default="{ row }">
              <div class="but_Settings">
                <button @click="reviseTerritory(1, row)" class="btn_Binding">
                  <span>修改</span>
                </button>
                <button @click="openDelest(row)" class="btn_delete">
                  <span>删除</span>
                </button>
                <button @click="toDetails(row)" class="btn_Modification">
                  <span>查看</span>
                </button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page" style="z-index: 999">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog :title="title" v-model="dialogFormVisible" width="50%">
        <el-form :model="form" style="display: flex; justify-content: center">
          <el-row>
            <!-- 左边 -->
            <el-col :span="12">
              <el-form-item label="阵地名:">
                <el-input
                  v-model="form.position_name"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="阵地所在省份:">
                <el-select
                  v-model="form.province"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in provinceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="阵地所在区:">
                <el-input v-model="form.district" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="状态:">
                <el-select
                  v-model="form.status"
                  placeholder="请选择"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="阵地简介:">
                <el-input
                  v-model="form.position_intro"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="红色文化亮点:">
                <el-input
                  v-model="form.culture_highlight"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="视频:">
                <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :show-file-list="false"
                  :limit="1"
                  :on-exceed="handleExceed"
                  @change="
                    (file) => {
                      handleFileChange(file, 'video_path');
                    }
                  "
                >
                  <div v-if="form.video_path">
                    <video
                      v-if="videoUrl == null"
                      :src="`http://127.0.0.1:8000${form.video_path}`"
                      controls=""
                      class="avatar"
                    />
                    <video v-else :src="videoUrl" class="avatar" />
                  </div>

                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
            <!-- 右边 -->
            <el-col :span="12">
              <el-form-item label="预约方式:">
                <el-input
                  v-model="form.reservation_method"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="参观时长:">
                <el-input
                  v-model="form.visit_duration"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="阵地地址:">
                <el-input
                  v-model="form.position_address"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="图片:">
                <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :show-file-list="false"
                  :limit="1"
                  :on-exceed="handleExceed"
                  @change="
                    (file) => {
                      handleFileChange(file, 'image_path');
                    }
                  "
                >
                  <div v-if="form.image_path">
                    <img
                      v-if="imageUrl == null"
                      :src="form.image_path"
                      class="avatar"
                    />
                    <img v-else :src="imageUrl" class="avatar" />
                  </div>

                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="展陈大纲:">
                <el-input
                  v-model="form.exhibition_outline"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <el-form-item label="坐标:">
                <el-input
                  v-model="form.coordinate"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="reset">取 消</el-button>
          <el-button type="primary" @click="onsubmit()">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 确认弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        width="500"
        :before-close="handleClose"
        style="margin-top: 15%"
      >
        <span>{{ dialogTitle }}</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="dialogVisible = false"
              v-if="dialogTitle == '你确认要上传该文件吗？'"
            >
              确定
            </el-button>
            <el-button type="primary" @click="Delete" v-else> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "../assets/componentStyles.css";
import {
  getAll,
  getTerritoryList, // 获取战地信息
  addTerritory, //新增战地信息
  PutTerritory, // 修改战地
  deleteTerritory, // 删除战地
} from "../api/territoryManagement.js";
import { ElMessage, genFileId } from "element-plus";
import Cookies from "js-cookie";

export default {
  data() {
    return {
      Loading: false,
      tableData: [{}], // 表格数据
      serch_position_name: "", //搜索的战地名称
      title: "", //弹窗标题
      dialogFormVisible: false, // 编辑弹窗控制变量
      dialogVisible: false, //确认弹窗控制变量
      dialog_status: null, // 新增修改的变量

      currentPage: 1, //页面
      page_size: 10, //当前页面条数
      total: 0, //总条数

      // 弹窗表单数据
      form: {
        position_name: "",
        province: "",
        district: "",
        status: "",
        position_intro: "",
        culture_highlight: "",
        video_path: "",
        reservation_method: "",
        visit_duration: "",
        position_address: "",
        image_path: "",
        exhibition_outline: "",
        coordinate: "",
        uploader: "",
        modifier: "",
      },
      excelFile: null, //excel文件

      // 省份选项
      provinceOptions: [],
      china: [
        "北京市",
        "天津市",
        "河北省",
        "山西省",
        "内蒙古自治区",
        "辽宁省",
        "吉林省",
        "黑龙江省",
        "上海市",
        "江苏省",
        "浙江省",
        "安徽省",
        "福建省",
        "江西省",
        "山东省",
        "河南省",
        "湖北省",
        "湖南省",
        "广东省",
        "广西壮族自治区",
        "海南省",
        "重庆市",
        "四川省",
        "贵州省",
        "云南省",
        "西藏自治区",
        "陕西省",
        "甘肃省",
        "青海省",
        "宁夏回族自治区",
        "新疆维吾尔自治区",
        "香港特别行政区",
        "澳门特别行政区",
        "台湾省",
      ],
      //状态选项
      statusOptions: [
        {
          value: 0,
          label: "开放",
        },
        {
          value: 1,
          label: "未开放",
        },
      ],
      dialogTitle: "", //确认弹窗文字
      deleteID: 0, //删除ID

      videoUrl: null, //视频回显路径
      imageUrl: null, //图片回显路径
    };
  },

  mounted() {
    this.china.forEach((element) => {
      this.provinceOptions.push({
        value: element,
        label: element,
      });
    });
    this.getList(this.currentPage, this.page_size);
  },

  methods: {
    // 获取数据
    getList(currentPage, page_size) {
      getTerritoryList({
        page: currentPage,
        pageSize: page_size,
      })
        .then((res) => {
          this.tableData = res.results;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          ElMessage.error(error);
        });
    },

    // 新增弹窗
    openAddTerritory(id) {
      this.dialog_status = id;
      this.reset(); //重置
      this.dialogFormVisible = true;
      this.title = "新增战地";
    },

    // 修改弹框
    reviseTerritory(id, row) {
      this.form = row;
      this.dialog_status = id;
      this.dialogFormVisible = true;
      this.title = "修改战地";
    },

    // 重置
    reset() {
      this.formInline = {
        name: "",
      };
      this.form.image_path = null;
      this.form.video_path = null;
      this.form = {
        position_name: "",
        province: "",
        district: "",
        status: "",
        position_intro: "",
        culture_highlight: "",
        video_path: "",
        reservation_method: "",
        visit_duration: "",
        position_address: "",
        image_path: "",
        exhibition_outline: "",
        coordinate: "",
        uploader: "",
        modifier: "",
      };
      this.page_size = 10;
      this.dialogFormVisible = false;
      this.getList(this.currentPage, this.page_size);
    },

    // 提交表单
    onsubmit() {
      this.form.uploader = Cookies.get("user_id");
      this.form.modifier = Cookies.get("user_id");
      const params = new FormData();
      // 新增
      if (this.dialog_status == 0) {
        Object.keys(this.form).forEach((key, index) => {
          params.append(String(key), this.form[key]);
        });
        addTerritory(params)
          .then((res) => {
            this.getList(this.currentPage, this.page_size);
            this.dialogFormVisible = false;
            ElMessage({
              message: "新增成功",
              type: "success",
            });
          })
          .catch((err) => {
            ElMessage({
              message: "请检查您上传的数据或稍后再试",
              type: "error",
            });
          });
      }
      // 修改
      else if (this.dialog_status == 1) {
        Object.keys(this.form).forEach((key, index) => {
          params.append(String(key), this.form[key]);
          console.log(this.form[key]);
        });
        try {
          PutTerritory(this.form.id, params)
            .then((res) => {
              this.getList(this.currentPage, this.page_size);
              this.dialogFormVisible = false;
              ElMessage({
                message: "修改成功",
                type: "success",
              });
            })
            .catch((error) => {
              ElMessage({
                message: error,
                type: "error",
              });
            });
        } catch (error) {}
      }
    },

    openDelest(row) {
      this.dialogTitle = "您确定要删除" + row.position_name + "这条数据吗？";
      this.dialogVisible = true;
      this.deleteID = row.id;
    },

    // 删除单行数据
    Delete() {
      deleteTerritory(this.deleteID)
        .then((res) => {
          this.dialogVisible = false;
          this.getList(this.currentPage, this.page_size);
          ElMessage({
            message: "成功删除" + row.position_name + "的战地数据·",
            type: "success",
          });
        })
        .catch((error) => {});
    },

    // 搜索方法
    search() {
      if (this.serch_position_name == "") return;
      getAll().then((res) => {
        this.tableData = res.filter((item) => {
          let state = true;
          let itemValue = item.position_name;
          if (!itemValue.includes(this.serch_position_name)) {
            this.state = false;
            return;
          }
          return state;
        });
        this.serch_position_name = "";
      });
    },

    // 当前页条数改变时调用
    handleSizeChange(val) {
      this.currentPage = 1;
      this.page_size = val;
      this.getList(this.currentPage, this.page_size);
    },

    // 当前页码改变时调用
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(this.currentPage, this.page_size);
    },

    // 上传文件
    handleExceed(files) {
      this.$refs.upload.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      this.$refs.upload.handleStart(file);
    },
    handleFileChange(event, status) {
      if (status == "excel") {
        this.excelFile = event.raw;
        this.dialogVisible = true;
        this.dialogTitle = "你确认要上传该文件吗？";
      } else if (status == "video_path") {
        this.form.video_path = event.raw;
        this.videoUrl = URL.createObjectURL(this.form.video_path);
      } else if (status == "image_path") {
        this.form.image_path = event.raw;
        this.imageUrl = URL.createObjectURL(this.form.image_path);
      }
    },

    // 跳转详情页
    toDetails(row) {
      this.$router.push({
        name: "details",
        query: row,
      });
    },
  },
};
</script>


<style lang="less" scoped>
.el-form-item {
  margin: 10px;
}
/deep/ .el-form-item__label {
  width: 176px;
  min-width: 76px;
  font-size: 16px;
  justify-content: flex-start;
}
.table {
  margin-top: 40px;
}
.el-form {
  display: flex;
}
/deep/.el-form-item__content {
  align-content: flex-start;
}
.upload {
  width: 100px;
}
/deep/.el-upload-list {
  margin: 0;
}
/deep/.el-table td.el-table__cell div {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
/deep/.btn_Modification,
.btn_delete,
.btn_Binding {
  margin: 0 10px;
}

// 图片上传
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader {
  margin-right: auto;
}
/deep/ .el-upload {
  border: 1px dashed var(--el-border-color) !important;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>>
